var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser= require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var goodsRouter = require('./routes/goods');
var orderRouter = require('./routes/order');
var roleRouter = require('./routes/role');
var uploadRouter = require('./routes/upload');
var mongoose= require('./config/mongoose.js');
var db=mongoose();
var cors = require('cors')
var app = express();
require("body-parser-xml")(bodyParser);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.xml({
  limit: "1MB",   // Reject payload bigger than 1 MB
  xmlParseOptions: {
    normalize: true,     // Trim whitespace inside text nodes
    normalizeTags: true, // Transform tags to lowercase
    explicitArray: false // Only put nodes in array if >1
  },
  verify: function(req, res, buf, encoding) {
    if(buf && buf.length) {
      // Store the raw XML
      req.rawBody = buf.toString(encoding || "utf-8");
    }
  }
}));
app.use(bodyParser.urlencoded({ extended: false}));
app.use(bodyParser.json());
app.use(express.json());
//app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/index', indexRouter);
app.use('/users', usersRouter);
app.use('/goods', goodsRouter);
app.use('/order', orderRouter);
app.use('/role', roleRouter);
app.use('/upload', uploadRouter);

//允许跨域
// app.use(bodyParser.xml({
//   limit: '1MB',   // Reject payload bigger than 1 MB 
//   xmlParseOptions: {
//     normalize: true,     // Trim whitespace inside text nodes 
//     normalizeTags: true, // Transform tags to lowercase 
//     explicitArray: false // Only put nodes in array if >1 
//   }
// }));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  //.log(req);
  //console.log(res);
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;
